#include "xboxcontroller.h"

#pragma comment(lib, "XInput.lib")

XBoxController::XBoxController(int playerNumber, QObject *parent)
  : InputDevice(parent), _controllerNum(playerNumber - 1), _currentPacket(0)
{
}

void XBoxController::init(OIS::InputManager *mgr)
{
}

void XBoxController::capture()
{
  XINPUT_STATE state = getState();
  if (state.dwPacketNumber == 0 || state.dwPacketNumber == _currentPacket)
    return;
  _currentPacket = state.dwPacketNumber;

   SHORT xValue = state.Gamepad.sThumbLX;
   SHORT yValue = state.Gamepad.sThumbLY;

   if (state.Gamepad.wButtons & XINPUT_GAMEPAD_A)
   {
     emit key(Ak_Enter);
   }
   else if (state.Gamepad.wButtons & XINPUT_GAMEPAD_B)
   {
     emit key(Ak_Back);
   }
   else if (abs(yValue) > 32000)
   {
     stopKeyEmit();
     _currentKey = (yValue > 0 ? Ak_Up : Ak_Down);
     startKeyEmit();
   }
   else if (abs(xValue) > 32000)
   {
     stopKeyEmit();
     _currentKey = (yValue > 0 ? Ak_Left : Ak_Right);
     startKeyEmit();
   }
   else if (yValue <= 32000 && xValue <= 32000 && (_currentKey == Ak_Up || _currentKey == Ak_Down || _currentKey == Ak_Left || _currentKey == Ak_Right))
   {
     stopKeyEmit();
   }
}

XINPUT_STATE XBoxController::getState()
{
  // Zeroise the state
  ZeroMemory(&_controllerState, sizeof(XINPUT_STATE));
  // Get the state
  XInputGetState(_controllerNum, &_controllerState);
  return _controllerState;
}

bool XBoxController::isConnected()
{
  // Zeroise the state
  ZeroMemory(&_controllerState, sizeof(XINPUT_STATE));
  // Get the state
  return XInputGetState(_controllerNum, &_controllerState) == ERROR_SUCCESS;
}

void XBoxController::vibrate(int leftVal, int rightVal)
{
  // Create a Vibraton State
  XINPUT_VIBRATION vibration;
  // Zeroise the Vibration
  ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION));
  // Set the Vibration Values
  vibration.wLeftMotorSpeed = leftVal;
  vibration.wRightMotorSpeed = rightVal;
  // Vibrate the controller
  XInputSetState(_controllerNum, &vibration);
}
